<?php
namespace app\api\controller;
use app\model\WxActivity as WxActivityModel;
use app\model\Token as TokenModel;
use think\Db;

use app\common\wechat\Pay;

class WxActivity extends Base
{   
    protected $noCheckToken = ['index','read','wxPayCallback'];

    /**
     * @Author   CCH
     * @DateTime 2020-05-23T12:10:10+0800
     * @return   数据列表
     */
    public function index(){
        $user_id = $this->login_user['user_id'];
        $map_params = [
            ['key'=>'activity_category_id','type'=>'='],
            ['key'=>'type','type'=>'='],
        ];
        $map = getSearchParam($map_params);
        if ( isSearchParam('keyword_search') ) {
            $map[] = ['name','like','%'.input('keyword_search').'%'];
        }
        if (input('is_home',0) == 1) {
            
        }
        $order_type = 'sort desc,id desc';

        $model = new WxActivityModel();
        $page_param = ['page'=>input('page_index',1),'list_rows'=>input('page_size',10)];
        $list = $model->where($map)->order($order_type)->paginate($page_param)->toarray();
        foreach ($list['data'] as $k => $vo) {
            if (!empty($vo['tags'])) {
                $list['data'][$k]['tags'] = explode(',',$vo['tags']);
            }else{
                $list['data'][$k]['tags'] = [];
            }
            
            if (!empty($user_id)) {
                $list['data'][$k]['is_apply'] = Db::name('wx_uactivity')->where([
                    ['user_id','=',$user_id],
                    ['status','<>',-1],
                    ['wx_activity_id','=',$vo['id']]
                ])->count() > 0 ? 1 : 0;
            }
            
            $user_ids = Db::name('wx_uactivity')->where([
                ['status','<>',-1],
                ['wx_activity_id','=',$vo['id']]
            ])->column('user_id');
            $users = [];
            if (!empty($user_ids)) {
                $users = Db::name('user')->field('id,nickname,headimgurl')->where('id','in',$user_ids)->limit(8)->select();
            }
            $list['data'][$k]['users'] = $users;
            $list['data'][$k]['apply_num'] = count($user_ids);
        }
        return apiResult('2000','获取成功',$list);
    }

    /**
     * 获取详情
     * @Author   cch
     * @DateTime 2020-05-26T17:22:45+0800
     * @return   [type]                   [description]
     */
    public function read($id){
        $user_id = $this->login_user['user_id'];
        $model = new WxActivityModel();
        $data = $model->where('id',$id)->find();
        if (!empty($data)) {
            if (!empty($data['images'])) {
                $data['images'] = explode(',',$data['images']);
            }else{
                $data['images'] = [];
            }
            if (!empty($data['tags'])) {
                $data['tags'] = explode(',',$data['tags']);
            }else{
                $data['tags'] = [];
            }
            if (!empty($user_id)) {
                $data['is_apply'] = Db::name('wx_uactivity')->where([
                    ['user_id','=',$user_id],
                    ['status','<>',-1],
                    ['wx_activity_id','=',$data['id']]
                ])->count() > 0 ? 1 : 0;

                $data['is_pay'] = Db::name('wx_activity_pay')->where([
                    ['user_id','=',$user_id],
                    ['status','=',1],
                    ['wx_activity_id','=',$data['id']]
                ])->count() > 0 ? 1 : 0;
            }
            
            $user_ids = Db::name('wx_uactivity')->where([
                ['status','<>',-1],
                ['wx_activity_id','=',$data['id']]
            ])->column('user_id');
            $users = [];
            if (!empty($user_ids)) {
                $users = Db::name('user')->field('id,nickname,headimgurl')->where('id','in',$user_ids)->select();
            }
            $data['users'] = $users;

            $data['is_field'] = Db::name('wx_activity_field')->where('wx_activity_id',$data['id'])->count() > 0 ? 1 : 0;

            $model->where('id',$id)->inc('view_num')->update();
        }
        
        return apiResult('2000','获取成功',$data);
    }

    /**
     * 点赞
     * @Author   cch
     * @DateTime 2020-05-26T17:22:45+0800
     * @return   [type]                   [description]
     */
    public function like($id){
        $model = new WxActivityModel();
        $model->where('id',$id)->inc('like_num')->update();
        
        return apiResult('2000','点赞成功');
    }

    /**
     * 点赞
     * @Author   cch
     * @DateTime 2020-05-26T17:22:45+0800
     * @return   [type]                   [description]
     */
    // public function apply($id){
    //     $data = Db::name('wx_activity')->where('id',$id)->find();
    //     if ($data['status'] != 0) {
    //         return apiResult('5000','当前活动已结束报名');
    //     }
    //     if ($data['apply_date'] < date('Y-m-d')) {
    //         return apiResult('5000','当前活动已超过报名日期');
    //     }

    //     $user_id = $this->login_user['user_id'];
    //     if (Db::name('wx_uactivity')->where([
    //         ['user_id','=',$user_id],
    //         ['status','<>',-1],
    //         ['wx_activity_id','=',$id]
    //     ])->count() == 0) {
    //         $save_data = [
    //             'wx_activity_id'=>$id,
    //             'user_id'=>$user_id,
    //             'ctime'=>time()
    //         ];
    //         Db::name('wx_uactivity')->insert($save_data);
    //     }
        
    //     return apiResult('2000','报名成功');
    // }

    /**
     * 点赞
     * @Author   cch
     * @DateTime 2020-05-26T17:22:45+0800
     * @return   [type]                   [description]
     */
    public function apply(){
        $param = file_get_contents('php://input');
        $param = json_decode($param,true);
        $fields = [
            'must'=>['wx_activity_id'],
            'nomust'=>['fields']
        ];
        $save_data = paramFilter($param,$fields);
        if (!empty($save_data['error_msg'])) {
            return apiResult('5000',$save_data['error_msg']);
        }
        if (!empty($save_data['fields'])) {
            if (is_array($save_data['fields'])) {
                $save_data['fields'] = json_encode($save_data['fields'],JSON_UNESCAPED_UNICODE);
            }
            $fields = json_decode($save_data['fields'],true);
            foreach ($fields as $k => $vo) {
                if ( empty($vo['value']) && $vo['value'] != '0' && Db::name('wx_activity_field')->where([
                    ['wx_activity_id','=',$save_data['wx_activity_id']],
                    ['name','=',$vo['name']]
                ])->value('is_must') == 1 ) {
                    return apiResult('5000',$vo['name'].'不能为空');
                }

                if (in_array($vo['name'], ['手机','电话','手机号码','手机号','联系电话']) && !isMobile($vo['value'])) {
                    return apiResult('5000',$vo['name'].'格式错误');
                }
            }
            
        }

        $user_id = $this->login_user['user_id'];
        $data = Db::name('wx_activity')->where('id',$save_data['wx_activity_id'])->find();
        if ($data['status'] != 0) {
            return apiResult('5000','当前活动已结束报名');
        }
        if ($data['apply_date'] < date('Y-m-d')) {
            return apiResult('5000','当前活动已超过报名日期');
        }

        $user_num = Db::name('wx_uactivity')->where([
            ['status','<>',-1],
            ['wx_activity_id','=',$data['id']]
        ])->count();
        if ($user_num >= $data['num']) {
            return apiResult('5000','当前活动人数已满');
        }

        if ($data['price'] > 0 && Db::name('wx_activity_pay')->where([
            ['user_id','=',$user_id],
            ['status','=',1],
            ['wx_activity_id','=',$data['id']]
        ])->count() == 0) {
            return apiResult('5000','该活动需先购买');
        }

        $map = [
            ['user_id','=',$user_id],
            ['status','<>',-1],
            ['wx_activity_id','=',$save_data['wx_activity_id']]
        ];
        if (Db::name('wx_uactivity')->where($map)->count() == 0) {
            $save_data['user_id'] = $user_id;
            $save_data['ctime'] = time();
            Db::name('wx_uactivity')->insert($save_data);
        }else{
            Db::name('wx_uactivity')->where($map)->update($save_data);
        }
        
        return apiResult('2000','报名成功',[
            'activity_date'=>$data['activity_date'],
            'address'=>$data['address']
        ]);
    }

    /**
     * 点赞
     * @Author   cch
     * @DateTime 2020-05-26T17:22:45+0800
     * @return   [type]                   [description]
     */
    public function cancelApply($id){
        $user_id = $this->login_user['user_id'];
        Db::name('wx_uactivity')->where([
            ['user_id','=',$user_id],
            ['status','<>',-1],
            ['wx_activity_id','=',$id]
        ])->update(['status'=>-1]);

        return apiResult('2000','取消成功');
    }

    /**
     * 点赞
     * @Author   cch
     * @DateTime 2020-05-26T17:22:45+0800
     * @return   [type]                   [description]
     */
    public function pay(){
        $param = file_get_contents('php://input');
        $param = json_decode($param,true);
        $fields = [
            'must'=>['wx_activity_id']
        ];
        $save_data = paramFilter($param,$fields);
        if (!empty($save_data['error_msg'])) {
            return apiResult('5000',$save_data['error_msg']);
        }
      
        $user_id = $this->login_user['user_id'];
        $data = Db::name('wx_activity')->where('id',$save_data['wx_activity_id'])->find();
        if ($data['status'] != 0) {
            return apiResult('5000','当前活动已结束报名');
        }
        if ($data['apply_date'] < date('Y-m-d')) {
            return apiResult('5000','当前活动已超过报名日期');
        }
        if ($data['price'] <= 0) {
            return apiResult('5000','当前活动不需要支付');
        }
        if (Db::name('wx_activity_pay')->where([
            ['user_id','=',$user_id],
            ['status','=',1],
            ['wx_activity_id','=',$data['id']]
        ])->count() > 0) {
            return apiResult('5000','您已经支付过该活动');
        }

        $save_data['user_id'] = $user_id;
        $save_data['order_sn'] = uuidCreate();
        $save_data['price'] = $data['price'];
        $save_data['ctime'] = time();
        Db::name('wx_activity_pay')->insert($save_data);

        $config = config('config.wxpay');
        $appId = $config['appid'];
        $mchId = $config['mchid'];
        $payKey = $config['paykey'];
        // $notify_url = request()->domain().'/index.php/index/order/wxPayCallback';
        $notify_url = url('wxPayCallback',[],'',true);

        $uinfo = Db::name('user')->where('id',$save_data['user_id'])->find();
        $openid = $uinfo['openid'];
        // $openid = 'oRthX5JoIaoN6dCPwug0kJgoRLNs';

        $pay = new Pay($appId, $mchId, $payKey);
        $result = $pay->order($save_data['order_sn'],$save_data['price'],$openid,$data['name'].'活动报名费用','',2,$notify_url);
        if ($result['status'] == 1) {
            return apiResult('2000','提交成功',$result['data']);
        }else{
            return apiResult('5000',$result['msg']);
        }
    }

    public function wxPayCallback(){
        $xml = file_get_contents('php://input');
        Db::name('test')->insert([
            'content'=>$xml
        ]);
        $params = xmlToArray($xml);
        
        if($params['result_code']=='SUCCESS' && $params['return_code']=="SUCCESS"){
            $order_sn = $params['out_trade_no'];
            $data = Db::name('wx_activity_pay')->where('order_sn',$order_sn)->find();

            if ($data['status'] != 0) {
                exit();
            }
            
            $save_data = ['status'=>1,'trade_no'=>$params['transaction_id'],'pay_time'=>time()];
            if ( Db::name('wx_activity_pay')->where('id',$data['id'])->update($save_data) !== false ) {
                
            }
            return "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
        }
        return '';
    }
   


}
